import React, { Component } from "react";
import "./Style.css";
import GC from "@grapecity/spread-sheets";
import "@grapecity/spread-sheets-print";
import "@grapecity/spread-sheets-pdf";

// import data_gc1 from "../data/公车年度统计报告.json";
import data_gc1 from "../data/全国公车报告.json";
// import data_gc1 from "../data/zcs.gcTlp-0625.json";
// import data_gc1 from "../data/zcs.gcTlp-0625-1.json";
// import data_gc1 from "../data/zcs.26479660983928456419.json";
import ssjsonJqFm1 from "../data/封面久其.json";

import { flatAllCells, foreachSheetsCell } from "../util/format";
import { downloadByALink } from "../util";

export const ViewType = {
    default: "默认",
    // title: '标题',
    datatype: "数据类型",
    // formula: '运算公式',
    /**
     * 单元格公式，区域公式可能有问题
     */
    xlsformulas: "自带公式",
    dbtf: "存储表",
    dbfield: "存储表字段",
    // dbtable: '存储表名称',
    cellpos: "单元格定位",
};

GC.Spread.Sheets.productInfo.productVersion = "15.1.2";

// "zcs.jdcloud.com,479778615419354#B0134crwGcrRkeolzRBlkbtN6NrhnWJNESBJmaT9Uc6UmbiFDNNN5KYFDewF6LGN5aUZzKv9kUZZjN8EjargHb78GbppVVPNTU6hnZnFlRKZVe9YDT5hUZ9AjW6ZlREVGTkh6a8RzKMZWYt5URah5KNRjZ6B7aBBTeN5UTzFjQ4lXMJtkMLdlT6dWQXtUMxIFThJDTqJmRyMHaXNVWad4Vxc4bvcVVElHenp5ZIxmd7FXasZ7VudUbqhWTP9EdmpkS5dGMqF6KJRDO7hEcBNjZrJlQOFVex5kcY9EewInbuFGSN96UnF4SykWT6o6cBZHaRlGSZ5UZPV5VhlUYa5kaxQFbIhXW6d7KVFmI0IyUiwiI8EUQ9EjMCFjI0ICSiwyN8IzNycDOwQTM0IicfJye#4Xfd5nIMFUUTJiOiMkIsISNx8idgMlSgQWYlJHcTJiOi8kI1tlOiQmcQJCLiMDM7EjMwASNxYDMzIDMyIiOiQncDJCLiMTM9AzMyAjMiojIwhXRiwiIt36YuQWdvx6YkpmLzNmeiojIz5GRiwiI8+Y9sWY9QmZ0Jyp9Aqo9Re09X6a9wWp9Jy11sqL9XyY9Iy11Cib9O+Z9ciL9sqL9iojIh94QiwiI4UzM9EDN5EjN8czN9cDNiojIklkIs4XXbpjInxmZiwSZzxWYmpjIyNHZisnOiwmbBJye0ICRiwiI34zZQZ6aMlHRvM7LtdTNGJDVQJnbyQjSNBVcwtEZv3kWC96YvkHZvZ7cyNVSOdUNiBVN73EORB7QoR4QVt4YNV6Rx8mZW5kYaRFbKJ7N"
const PROD_SPREAD_SEY =
    "zc.ggj.gov.cn,678359156589869#B0mSTLJjRFBlZyh6cDBnWplUd5N7STZFc0FUU8wmUzlkYqN6VxETdkRGRoFXRw8Gamt4Yj3mW4Y4T5IFMnJGRxQjWDR6SZdXQjJzUqVDdaJjTIZWZCF6R53GOuBTcJhTN6FHVR9mbIN5RGFjWjlFeDZjdjNlRuV7N5METxZzR4JVa9N5SlBDVuVjUUFDcOJFWnRGd8lVU6EVcEBjY7lnaxw4ZxkFNxV7UvlGe4gmUXFFNj5USqNXc4VVdyYTeW5mMlhHN6hEaIJzd7ZXO7NDaz3yUL96VZpWW5IjUzg7VHRGTXhjekJFRrc4ZwQTbQVDMmlzKSFnSrtiZ93iN8hlVkRmI0IyUiwiIFBjNBRDMCNjI0ICSiwiNykTM6UTNzATM0IicfJye&Qf35VfiwUQRNlI0IyQiwiI5EjL6ByUKBCZhVmcwNlI0IiTis7W0ICZyBlIsICO5ETNxADIxETMwQjMwIjI0ICdyNkIsIibj9idvdmLqd6ZuMmeiojIz5GRiwiI8+Y9sWY9QmZ0Jyp9Aqo9Re09X6a9wWp9Jy11sqL9XyY9Iy11Cib9O+Z9ciL9sqL9iojIh94QiwiI9YDO9gTN6UTM9UzM8cjNiojIklkIs4XXbpjInxmZiwSZzxWYmpjIyNHZisnOiwmbBJye0ICRiwiI34zd8Z7cp34LWJDc8ADaEJ4Qp3UOwM5SkJUQZR4Z9l4SyYXeMhleYpFS8EnayllMxY7c0ZGZ0dUWtdXNiRTTPFEU6M7VmF5V6dWUHJlTElEUElVbwAy2I";
// "zc.ggj.gov.cn,649745189477361#B0jpqWSSJmWKZ4d45GMyMFTIRUOVdWOkhke4oWOrEkYVJXVwlHNNVlevMWRqtmMk9Ub6sWWxc4bWtUdpFTSxsCclVmQwEFaxVWdKt6clh7ZvkWR8VUbxMlaT3WNQlUVPNTVx9kN7cjRsBVOYNVc5xWdHRlTap4MlV6NDdna8UUW8NEMJdjNkFXSN5kZ624RopnYVV6ZkNDSwtkY8F6KvdXQGRzaJhkdEVTS5xGS9knSiFzYqVlWxpUUpJkYvgneDdVZ4R7aQJzLOF6SZhkMrwUSrBTYzJHO92COSJ6c8kVbV34c8JnQzwEV9c6KMVEei3kYvw4QroXQYx6drp5KIlEWvcUUw2CMOFjalJiOiMlIsICNwEUOxAzNiojIIJCL4IDN8kTN6UTO0IicfJye&Qf35VfiwUQRNlI0IyQiwiI5EjL6ByUKBCZhVmcwNlI0IiTis7W0ICZyBlIsISNzMTMxADIxEzNwMjMwIjI0ICdyNkIsICMxgDMzIDMyIiOiAHeFJCLi86YuY7bn9iandmLjpnI0IyctRkIsICuPWOrFWOkZmeicaOgKaekne+ltWOsVaei2+Or0S+lMWOi2+ug8WujfWOn8SOr0SuI0ISYONkIsISM6MzN7QTO8ETN4cTO4YjI0ICZJJCL355W0IyZsZmIsU6csFmZ0IiczRmI1pjIs9WQisnOiQkIsISP3E5LhhmaQJHVBp4YuRGZ5IWUktGZUl5M7YTVCVWeCFFR6QzcwxmdxgUM596LHBlcMhnTN5Wc9pUYWFUYJJDUmVXYIRWMBl7LJNFHVo3";
GC.Spread.Sheets.LicenseKey = PROD_SPREAD_SEY;
// GC.Spread.Sheets.__defineGetter__("LicenseKey", function () {
//     debugger;
//     return PROD_SPREAD_SEY;
// });

class SheetGC extends Component {
    /** @type {GC.Spread.Sheets.Workbook} */
    spread = null;
    sheetTplRef = { current: {} };

    constructor(props) {
        super(props);
        this.state = {
            viewType: "default",
            data: undefined,

            columnPageBreak: [],
            zoomFactor: 100,
            fitPagesWide: "",
            paperSize: "a4",
        };
    }

    ev = {
        BeforePrint: {
            name: GC.Spread.Sheets.Events.BeforePrint,
            handle: function (ev, data) {
                if (!window.__isNative) {
                    return;
                }

                // electron 中，基本无法设置页边距
                /** @type {HTMLIFrameElement} */
                const sjsiframe = data.iframe;

                const isPreview = true;
                if (isPreview) {
                    sjsiframe.style.width = "800px";
                    sjsiframe.style.height = "600px";
                    sjsiframe.style.position = "fixed";
                    sjsiframe.style.top = "200px";
                    sjsiframe.style.left = "200px";
                    sjsiframe.style.background = "#ffffff";
                }

                var style = sjsiframe.contentDocument.createElement("style");
                style.type = "text/css";
                // style.innerHTML = "@page { size: A4 landscape; margin: 0 };";
                style.innerHTML = "@page { size: landscape; margin: 0 };";
                sjsiframe.contentDocument.getElementsByTagName("head")[0].appendChild(style);
                window.printIfr = sjsiframe.contentWindow;

                // sjsiframe.contentWindow.print();
                myAPI.print({ htmlContent: sjsiframe.contentDocument.getElementsByTagName("html")[0].innerHTML });

                setTimeout(() => {
                    sjsiframe.remove();
                }, 30);
                // document.body.append(sjsiframe);
                data.cancel = true;
            },
        },
    };
    initSpread = () => {
        // 注释
        const sheetDom = document.getElementById("SheetGC");
        const sheetRect = sheetDom.getBoundingClientRect();

        var spread = new GC.Spread.Sheets.Workbook(sheetDom);
        var statusBar = new GC.Spread.Sheets.StatusBar.StatusBar(document.getElementById("SheetGcStatus"));
        statusBar.bind(spread);

        this.spread = spread;

        // 设置表格属性
        // spread.options.newTabVisible = false;
        // spread.options.tabEditable = false;
        // spread.options.allowSheetReorder = false;

        // 绑定表格事件
        spread.bind(GC.Spread.Sheets.Events.ActiveSheetChanging, (event, data) => {
            this.setViewType(data.newSheet.name());
        });
        spread.bind(this.ev.BeforePrint.name, this.ev.BeforePrint.handle);

        const _print = window.print;
        window.print = function () {
            console.log(1);
            _print();
        };

        var oldEvent = EventTarget.prototype.addEventListener;
        EventTarget.prototype.addEventListener = function (type, _fn, opt) {
            // console.log('addEventListener',...args)
            var fn = _fn;
            if (type === "mousewheel") {
                fn = function (ev) {
                    // 感觉有时候生效，有时候不生效
                    spread.options.scrollByPixel = true;
                    if (ev.currentTarget.id.indexOf("vp_vp") > -1) {
                        if (ev.altKey || ev.shiftKey) {
                            var scrollDelta = ev.wheelDelta;
                            // spread.getActiveSheet().scroll(0, scrollDelta)
                            spread.getActiveSheet().scroll(0, scrollDelta);
                            return;
                        }
                    }
                    _fn(ev);
                };
            }
            oldEvent.call(this, type, fn, opt);
        };
        // spread.bind(GC.Spread.Sheets.Events.SheetChanged, (event, data) => {
        //     if (data.newValue) {
        //         setTimeout(() => {
        //             var canDom = document.getElementById(sheetDom.id + 'vp_vp')
        //             canDom.addEventListener('mousewheel', (ev) => {
        //                 getEventListeners(canDom).mousewheel = []

        //                 // sheetDom.addEventListener('mousewheel', (ev) => {
        //                 if (ev.altKey || ev.shiftKey) {
        //                     const scrollDelta = ev.deltaX || ev.deltaY; // 有些浏览器可能使用deltaX，有些可能使用deltaY，这里做兼容处理

        //                     spread.getActiveSheet().scroll(0, scrollDelta)
        //                 } else if (!ev.ctrlKey) {
        //                     const scrollDelta = ev.deltaX || ev.deltaY; // 有些浏览器可能使用deltaX，有些可能使用deltaY，这里做兼容处理

        //                     spread.getActiveSheet().scroll(scrollDelta, 0)
        //                 }
        //             })
        //         }, 100)
        //     }

        // })
        document.getElementById(sheetDom.id + "_tabStrip").onmousewheel = function (args) {
            var workbook = spread;
            //判断tab标签页位置是在上方或者下方，避免影响原有的左右两侧的滚动逻辑
            if (workbook.options.tabStripPosition == GC.Spread.Sheets.TabStripPosition.bottom || workbook.options.tabStripPosition == GC.Spread.Sheets.TabStripPosition.top) {
                //判断滚动方向
                if (args.deltaY > 0 && workbook.startSheetIndex() < workbook.getSheetCount() - 1) {
                    //调用startSheetIndex改变第一个标签的index
                    workbook.startSheetIndex(workbook.startSheetIndex() + 1);
                } else if (args.deltaY < 0 && workbook.startSheetIndex() > 0) {
                    workbook.startSheetIndex(workbook.startSheetIndex() - 1);
                }
            }
        };

        // alt+pageup/pagedown实现换页
        let pageDown = {
            canUndo: false,
            name: "pageDown",
            execute: function (context, options, isUndo) {
                let Commands = GC.Spread.Sheets.Commands;
                Commands.startTransaction(context, options);
                context.getActiveSheet().scroll(0, context.getHost().clientWidth - context.getActiveSheet().getColumnWidth(0, GC.Spread.Sheets.SheetArea.rowHeader));
                Commands.endTransaction(context, options);
                return true;
            },
        };
        let pageUp = {
            canUndo: false,
            name: "pageUp",
            execute: function (context, options, isUndo) {
                let Commands = GC.Spread.Sheets.Commands;
                Commands.startTransaction(context, options);
                context.getActiveSheet().scroll(0, -context.getHost().clientWidth + context.getActiveSheet().getColumnWidth(0, GC.Spread.Sheets.SheetArea.rowHeader));
                Commands.endTransaction(context, options);
                return true;
            },
        };
        spread.commandManager().register("pageDown", pageDown, GC.Spread.Commands.Key.down, false, false, true, false);
        spread.commandManager().register("pageUp", pageUp, GC.Spread.Commands.Key.up, false, false, true, false);

        this.setFileData();
    };
    setLocalData = () => {
        var spreadJson = JSON.parse(localStorage.getItem("spreadJson"));
        this.spread.fromJSON(spreadJson);
    };
    setFileData = () => {
        var data = data_gc1.data || data_gc1;

        var sheetInfo = JSON.parse(data.sheetInfo);
        var bindInfo = JSON.parse(data.bindInfo);
        var sourceData = JSON.parse(data.sourceData);

        this.loadedData(sourceData);

        console.log("all", {
            sheetInfo: data.sheetInfo,
            bindInfo: data.bindInfo,
            sourceData: data.sourceData,
        });

        console.log("sheetInfo: ", sheetInfo);
        console.log("bindInfo: ", bindInfo);
        console.log("sourceData: ", sourceData);
        window.spreadRe = {
            GC: GC,
            spread: this.spread,
            getActiveSheet: function () {
                return this.spread.getActiveSheet();
            },
            sheetInfo: sheetInfo,
            bindInfo: bindInfo,
            sourceData: sourceData,
        };

        this.spread.fromJSON(sheetInfo);
        window.spreadRe.sheet = this.spread.getActiveSheet();

        this.spread.bind(GC.Spread.Sheets.Events.ActiveSheetChanging, (ev, data) => {
            const newSheet = data.newSheet;
            const sc = this.sheetConf[newSheet.name()] || {};
            this.setState({ fitPagesWide: sc.fitPagesWide });
            window.spreadRe.sheet = newSheet;
            spreadRe.sheet.options.isProtected = false;
        });
    };

    loadedData = (sourceData) => {
        const workbookIns = this.spread;
        const sheetTplRef = this.sheetTplRef;

        workbookIns.suspendPaint();
        workbookIns.suspendCalcService(false);

        foreachSheetsCell(sourceData, (sheetName, rowIdx, colIdx) => {
            const sheet = sourceData[sheetName];
            const sheetIns = workbookIns.getSheetFromName(sheetName);
            if (!sheetIns) return; // sheet 重命名后，有一些脏数据
            const cell = sheet[rowIdx][colIdx];

            cell.formulas = sheetIns.getFormula(rowIdx, colIdx);
            sheetIns.setFormula(rowIdx, colIdx, "");
        });

        workbookIns.resumeCalcService(false);
        workbookIns.resumePaint();

        sheetTplRef.current.sourceData = sourceData;
        sheetTplRef.current.allCells = flatAllCells(sourceData);

        console.log("模板数据加载完成 ===>", workbookIns, sheetTplRef.current.allCells);
    };

    onChangeViewType = (e) => {
        this.setState({ viewType: e.target.value }, () => {
            this.setViewType();
        });
    };

    setViewType = (sheetName) => {
        const viewType = this.state.viewType;
        const sheetTplRef = this.sheetTplRef;

        // const _disData = props.data;
        const _disData = this.state.data;
        console.log("设置视图===>");
        // const sheetsIns = sheetTplRef.current.instance;
        const sheetsIns = this.spread;
        if (!sheetsIns) return;

        let curSheetName = sheetName;
        if (!sheetName) {
            curSheetName = sheetsIns.getActiveSheet().name();
        }
        if (!curSheetName) return;
        const curSheet = sheetsIns.getSheetFromName(curSheetName);

        const allCells = sheetTplRef.current.allCells;
        if (!allCells || !curSheet) return;
        console.log("视图类相关 ===>", viewType, _disData);

        if (viewType === "xlsformulas") {
            curSheet.options.showFormulas = true;
        } else {
            curSheet.options.showFormulas = false;
        }
        sheetsIns.suspendPaint();
        sheetsIns.suspendCalcService(false);
        sheetsIns.suspendEvent();
        const sheetCells = allCells[curSheetName] || [];
        sheetCells.map((cell) => {
            let val = "";

            if (cell.formulas) {
                if (viewType === "default" || viewType === "xlsformulas") {
                    curSheet.setFormula(cell.posRow, cell.posCol, cell.formulas);
                } else {
                    curSheet.setFormula(cell.posRow, cell.posCol, "");
                }
            }

            switch (viewType) {
                case "default":
                    // val = '';
                    if (!(_disData && _disData[cell.tableName] && _disData[cell.fieldName])) {
                        return;
                    }
                    val = _disData[cell.tableName][cell.fieldName];
                    break;
                case "datatype":
                    val = cell.dataType;
                    break;
                case "dbtf":
                    val = `[${cell.tableName}, ${cell.fieldName}]`;
                    break;
                case "dbtable":
                    val = cell.tableName;
                    break;
                case "dbfield":
                    val = cell.fieldName;
                    break;
                case "cellpos":
                    val = `[${cell.posRow}, ${cell.posCol}]`;
                    break;
                default:
                    break;
            }
            curSheet.setValue(cell.posRow, cell.posCol, val);
        });
        sheetsIns.resumeCalcService(false);
        sheetsIns.resumePaint();
        sheetsIns.resumeEvent();
    };

    componentDidMount() {
        this.initSpread();
    }

    setPageBreak = (type) => {
        var sheet = this.spread.getActiveSheet();

        var oldColPageBreak = this.state.columnPageBreak || [];
        var columnPageBreak = sheet.getSelections().map((v) => v.col);
        if (type === "set") {
            sheet.isPrintLineVisible(true);
            if (columnPageBreak.length) {
                columnPageBreak.map((v) => {
                    oldColPageBreak = [...new Set([...oldColPageBreak, v])];
                    sheet.setColumnPageBreak(v, true);
                });
            }
        } else if (type === "remove") {
            if (columnPageBreak.length) {
                columnPageBreak.map((v) => {
                    oldColPageBreak = oldColPageBreak.filter((a) => a !== v);
                    sheet.setColumnPageBreak(v, false);
                });
            }
        } else if (type === "removeAll") {
            oldColPageBreak.map((v) => {
                sheet.setColumnPageBreak(v, false);
            });
            oldColPageBreak = [];
        }
        this.setState({ columnPageBreak: oldColPageBreak });
    };

    /** 
     *  //     tableName: '表名', 默认当前sheet页名称
        //     tableType: '汇总01表'
        //     fitPagesWide: '整行分为几页打印',
        //     hasNotesRow: '是否有备注行'
     */
    sheetConf = {
        封面: {},
        定向化保障用车明细表: { tableType: "明细表1-1", fitPagesWide: "2", hasNotesRow: true, rowHeight: 28, rowTitle: [0, 1] },
        定向化保障用车变动情况明细表: { tableType: "", fitPagesWide: 3, hasNotesRow: true },
        党政机关公务用车分级汇总表: { fitPagesWide: 1, hasNotesRow: true, rowHeight: 28 },
        党政机关公务用车情况分类汇总表: { fitPagesWide: 1 },
        党政机关公务用车变动汇总表: { fitPagesWide: 2, hasNotesRow: true },
        事业单位公务用车情况分级汇总表: { fitPagesWide: 2, rowHeight: 28 },
        事业单位公务用车情况分类汇总表: { fitPagesWide: 1 },
        事业单位公务用车变动汇总表: { fitPagesWide: 2, hasNotesRow: true },
        越野车配备情况: { fitPagesWide: 1, hasNotesRow: true },
        越野车配备情况明细表: { fitPagesWide: 1, hasNotesRow: true },
        省部级干部用车配备使用情况明细表: { fitPagesWide: 2, hasNotesRow: 1 },
        监督检查工作情况: { fitPagesWide: 1, hasNotesRow: true },
        监督检查工作情况明细表: { fitPagesWide: 1, hasNotesRow: true },
    };
    handleSetPrintInfo = () => {
        const sheetConf = this.sheetConf;
        const orgName = "xxx 单位";
        this.orgName = orgName;

        const spread = this.spread;
        const spreadEnd = spread;
        const sheet = spreadEnd.getActiveSheet();
        const sheetName = sheet.name();
        const tablePrintInfo = sheetConf[sheetName] || {};

        sheet.suspendPaint();

        /** @type {GC.Spread.Sheets.Print.PrintInfo} */
        const printInfo = sheet.printInfo();
        spreadEnd.getActiveSheet().isPrintLineVisible(true);
        // 打印基本设置
        // printInfo.bestFitColumns(true);
        // printInfo.blackAndWhite(true); //彩色打印还是黑白打印（true为黑白打印，false为彩色打印）
        printInfo.showRowHeader(GC.Spread.Sheets.Print.PrintVisibilityType.hide);
        printInfo.showColumnHeader(GC.Spread.Sheets.Print.PrintVisibilityType.hide);
        printInfo.margin({ top: 60, bottom: 10, left: 10, right: 10, header: 0 });
        // printInfo.margin({});
        // printInfo.paperSize(new GC.Spread.Sheets.Print.PaperSize(GC.Spread.Sheets.Print.PaperKind.a3));
        if (this.state.paperSize) {
            printInfo.paperSize(new GC.Spread.Sheets.Print.PaperSize(GC.Spread.Sheets.Print.PaperKind[this.state.paperSize]));
        }
        // printInfo.paperSize(new GC.Spread.Sheets.Print.PaperSize(1100, 2060)); //a4 应该为800,1060，但是宽度存在空白,所以设置为1560
        printInfo.orientation(GC.Spread.Sheets.Print.PrintPageOrientation.landscape);
        printInfo.pageOrder(GC.Spread.Sheets.Print.PrintPageOrder.overThenDown);
        printInfo.qualityFactor(8);
        // printInfo.zoomFactor(0.4)
        printInfo.showGridLine(true);
        printInfo.showBorder(true); //是否显示边框

        printInfo.headerLeft(["", "编制单位：" + orgName].join("\r\n"));
        // &18 字大小 &"Calibri" 字体 &K000000 字色
        printInfo.headerCenter('&18&"Calibri"&K000000' + (tablePrintInfo.tableName || sheetName || "无"));
        printInfo.headerRight(["", "&12&K000000" + (tablePrintInfo.tableType || ""), "金额单位：" + (tablePrintInfo.unit || "元")].join("\r\n"));

        if (tablePrintInfo.rowTitle) {
            printInfo.repeatRowStart(tablePrintInfo.rowTitle[0]);
            printInfo.repeatRowEnd(tablePrintInfo.rowTitle[1]);
        }

        // 默认整个表，(sheet.getRowCount() - 1)
        if (tablePrintInfo.hasNotesRow) {
            printInfo.rowEnd(sheet.getRowCount() - 2);
        }
        // if (tablePrintInfo.fitPagesWide) {
        // 分几打印完成，默认按照原始大小自动分，设置后可能会缩放导致打印模糊
        // printInfo.fitPagesWide(this.state.fitPagesWide || tablePrintInfo.fitPagesWide);
        printInfo.fitPagesWide(this.state.fitPagesWide);
        // }
        // 缩放因子，与 fitPageWide 是互斥的；num*100=百分比
        printInfo.zoomFactor(this.state.zoomFactor / 100);
        // printInfo.centering(GC.Spread.Sheets.Print.PrintCentering.horizontal)

        // 设置指定列之前插入分页符
        // sheet.setColumnPageBreak(3.true)
        var columnPageBreak = this.state.columnPageBreak || [];
        if (columnPageBreak.length) {
            columnPageBreak.map((v) => {
                sheet.setColumnPageBreak(v, true);
            });
        }

        // 14.6667px Calibri
        // sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).font("14px Calibri");
        // sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).backColor('');
        // var _sheet = sheet
        // _sheet.defaults.rowHeight = 34;
        // var dStyle = _sheet.getDefaultStyle();
        // dStyle.vAlign = GC.Spread.Sheets.VerticalAlign.center;
        // _sheet.setDefaultStyle(dStyle)
        // _sheet.setDefaultStyle({ ..._sheet.getDefaultStyle(), vAlign: GC.Spread.Sheets.VerticalAlign.center })
        sheet.options.isProtected = false;
        // sheet.getRange(0, 0, sheet.getRowCount(), sheet.getColumnCount()).setBorder(
        //     new GC.Spread.Sheets.LineBorder("#8A2BE2", '1pt'), { all: true }
        // );

        sheet.resumePaint();
    };
    handlePrintData = (type) => {
        if (type === "electron") {
            myAPI?.print("deviceName");
            return;
        }

        function setPdfName(name = "") {
            if (name) {
                var oT = document.title;
                var t = setInterval(() => {
                    if (document.title !== oT) {
                        document.title = oT;
                        clearInterval(t);
                    }
                }, 300);
                document.title = oT;
            }
            document.title = name;
        }

        let spread = this.spread;
        let spreadEnd = spread;
        var sheet = spread.getActiveSheet();
        var name = sheet.name();
        var isPdf = type === "pdf";
        var isHtml = type === "html";

        var dom = document.createElement("div");
        dom.setAttribute("style", "width: 1800px; height: 1200px;position: relative;z-index: 100;background: #fff");
        // document.getElementsByClassName('app-container')[0].appendChild(dom)
        if (name === "封面") {
            var _spread = new GC.Spread.Sheets.Workbook(dom);
            _spread.suspendPaint();
            _spread.fromJSON(ssjsonJqFm1);
            var _sheet = _spread.getSheetFromName("封面表");

            var _sheetRange = _sheet.getRange(0, 0, _sheet.getRowCount(), _sheet.getColumnCount());
            _sheetRange
                // .font("14px 宋体")
                .backColor("")
                .cellButtons([]);

            const d = {
                ID: 28,
                FMG16_2: "科技机构",
                FMG17_2: "承担行政职能",
                FMG19_2: "15",
                FMG18_2: "参公管理财政补助",
                FMG20_2: "1",
                FMG10_2: "111",
                FMG22_2: "2024-03-20 16:15:13",
                FMG11_2: "222",
                FMG21_2: "单户表",
                FMG12_2: null,
                FMG13_2: null,
                FMG23_2: null,
                FMG14_2: "县一级(本级)",
                FMG15_2: "行政机关",
                FMG2_2: "李凌云",
                FMG1_2: "成都市锦江区人力资源和社会保障局",
                FMG4_2: "86620961",
                FMG3_2: "王晶梅",
                FMG6_2: "86757650",
                FMG5_2: "陈浩",
                FMG8_2: "11510104009182859M",
                FMG7_2: "009182859",
                FMG9_2: "000",
                CREATE_USERID: "42953",
                CREATE_TIME: "2024-03-12T11:56:43.000+00:00",
                UPDATE_USERID: "42867",
                UPDATE_TIME: "2024-03-20T08:15:14.000+00:00",
                CREATE_USERORG: "009182859",
                BELONG_ORG_ID: "423317",
                BELONG_ORG_PID: "423270",
                BELONG_ORG_NAME: "成都市锦江区人力资源和社会保障局",
                BELONG_ORG_CODE: "009182859",
                FMG16_2_HZ: "",
                FMG17_2_HZ: "",
                FMG19_2_HZ: "15",
                FMG18_2_HZ: "",
                FMG20_2_HZ: "1",
                FMG10_2_HZ: null,
                FMG22_2_HZ: "2024-01-19 17:46:41",
                FMG11_2_HZ: null,
                FMG21_2_HZ: "汇总表",
                FMG12_2_HZ: null,
                FMG13_2_HZ: null,
                FMG23_2_HZ: null,
                FMG14_2_HZ: "县一级(本级)",
                FMG15_2_HZ: "行政机关",
                FMG2_2_HZ: "李凌云",
                FMG1_2_HZ: "成都市锦江区人力资源和社会保障局",
                FMG4_2_HZ: null,
                FMG3_2_HZ: null,
                FMG6_2_HZ: null,
                FMG5_2_HZ: null,
                FMG8_2_HZ: "11510104009182859M",
                FMG7_2_HZ: "009182859",
                FMG9_2_HZ: null,
            };
            this.setDataSource(_sheet, d);
            this.setBindPath(_sheet, _spread);

            /** @type {GC.Spread.Sheets.Print.PrintInfo} */
            var printInfo = _sheet.printInfo();
            printInfo.showBorder(false);
            printInfo.showGridLine(false);

            window.spreadRe.spreadPrint = _spread;
            window.spreadRe.sheetPrint = _sheet;

            if (isPdf) {
                // .fontFamily() v17 才有
                for (let r = 0; r < _sheetRange.rowCount; r++) {
                    for (let c = 0; c < _sheetRange.colCount; c++) {
                        var of = _sheet.getCell(r, c).font() || "";
                        of = of.replace("Calibri", "宋体");
                        _sheet.getCell(r, c).font(of);
                    }
                }

                GC.Spread.Sheets.PDF.PDFFontsManager.registerFont("宋体", { normal: fonts["simkai.ttf"] });
                // GC.Spread.Sheets.PDF.PDFFontsManager.registerFont("宋体");

                _spread.savePDF(
                    (blob) => {
                        var href = window.URL.createObjectURL(blob);
                        downloadByALink({ url: href, fileName: name + ".pdf" });
                        window.URL.revokeObjectURL(href);
                    },
                    (err) => {
                        console.log("导出错误：", err);
                    },
                    undefined,
                    _spread.getSheetIndex(_sheet.name())
                );
                return;
            }

            _spread.resumePaint();
            setPdfName(name);

            _spread.bind(this.ev.BeforePrint.name, this.ev.BeforePrint.handle);
            _spread.print(_spread.getSheetIndex(_sheet.name()));
            return;
        } else {
            /** @type {GC.Spread.Sheets.Workbook} */
            var _spread = new GC.Spread.Sheets.Workbook(dom);
            var oJson = spread.toJSON();
            _spread.suspendPaint();
            // TODO: 不使用 parse 处理一下，可能会影响当前展示的表格的样式，待查原因
            _spread.fromJSON(JSON.parse(JSON.stringify(oJson)));
            // var _sheet = spread.getActiveSheet()
            var _sheet = _spread.getSheetFromName(name);
            // console.log(_sheet.toJSON(), _sheet);

            var _sheetRange = _sheet.getRange(0, 0, _sheet.getRowCount(), _sheet.getColumnCount());
            _sheetRange
                // .font("14px Calibri")
                // SIMHEI 字体偏大一些
                .font("12px 宋体")
                .backColor("")
                .cellButtons([]);
            _sheetRange.vAlign(GC.Spread.Sheets.VerticalAlign.center);
            // _sheet.defaults.rowHeight = 24;
            // _sheet.setDefaultStyle({ ..._sheet.getDefaultStyle(), vAlign: GC.Spread.Sheets.VerticalAlign.center })

            var sheetConf = this.sheetConf[name] || {};
            if (sheetConf.rowHeight) {
                // _sheet.defaults.rowHeight = 48
                // TODO: 现在是采用的一个空表做打印，这里可能会影响到显示的的表样式
                for (let i = 0; i < _sheet.getRowCount(); i++) {
                    _sheet.setRowHeight(i, sheetConf.rowHeight);
                    // _sheet.setRowHeight(i, 28)
                }
            }

            _spread.resumePaint();
            window.spreadRe.spreadPrint = _spread;
            window.spreadRe.sheetPrint = _sheet;

            if (isPdf) {
                // 页眉页脚等字体显示与内容不一样
                GC.Spread.Sheets.PDF.PDFFontsManager.registerFont("宋体", { normal: fonts["simkai.ttf"] });
                // GC.Spread.Sheets.PDF.PDFFontsManager.registerFont("Calibri", { normal: fonts["simkai.ttf"] });
                GC.Spread.Sheets.PDF.PDFFontsManager.fallbackFont = (font) => {
                    // 设置备选字体，比如Calibri不支持中文，才会走到这里
                    // 取消上边注册宋体。全部文字才会使用simhei渲染；
                    // if (!/Calibri|宋体/.test(font)) {
                    //     debugger // 页眉页脚是其他字体 Arial
                    // }

                    // 所有字体都使用此字体
                    // 这里使用黑体是测试那些字体与设置的不一样
                    return fonts["simhei.ttf"];
                    // return fonts["simkai.ttf"];

                    if (font.indexOf("Calibri") > -1) {
                        return fonts["simkai.ttf"];
                    }

                    return null;
                };
                _spread.savePDF(
                    (blob) => {
                        var href = window.URL.createObjectURL(blob);
                        downloadByALink({ url: href, fileName: name + ".pdf" });
                        window.URL.revokeObjectURL(href);
                    },
                    (err) => {
                        console.log("导出错误：", err);
                    },
                    undefined,
                    _spread.getSheetIndex(_sheet.name())
                );
                return;
            }

            if (isHtml) {
                var curPageInfo = _spread.pageInfo(_spread.getSheetIndex(_sheet.name()));
                var html = "";
                curPageInfo.pages.map((v) => {
                    var table = _sheet.getRange(v.row, v.column, v.rowCount, v.columnCount).toHtml();
                    html += `<div class="section">${table}</div>`;
                });

                var printWin = window.open("", "_blank");
                printWin.document.write(html);
                printWin.document.title = [this.orgName || "", name].filter((v) => v).join("-");
                return;
            }

            // const h = function (e) {
            //     console.log(e);

            //     window.removeEventListener("afterprint", h);
            // };
            // TODO: window 的事件不生效
            // window.addEventListener("afterprint", h);
            // _spread.bind(GC.Spread.Sheets.Events.BeforePrint, function (e, data) {
            //     alert(data.iframe + "\n" + "cancel: " + data.cancel);
            // });

            setPdfName([this.orgName || "", name].filter((v) => v).join("-"));

            _spread.bind(this.ev.BeforePrint.name, this.ev.BeforePrint.handle);
            _spread.print(_spread.getSheetIndex(name));
            return;
        }

        // spreadEnd.print(spreadEnd.getActiveSheetIndex(), printInfo);
        spreadEnd.print(spreadEnd.getActiveSheetIndex());

        // spreadEnd.savePDF(spreadEnd.getActiveSheetIndex(), printInfo);
        // const pdfOptions = new GC.Spread.Sheets.PDF.PDFOptions();
        // pdfOptions.autoFitType = GC.Spread.Sheets.PDF.AutoFitType.never;
        // pdfOptions.scaleFactor = 1.0;
        // pdfOptions.printInfo = printInfo;
        // spread.exportPdf({
        //   fileName: 'custom-pdf-export.pdf',
        //   pdfOptions: pdfOptions,
        // });
    };
    /** @param {import('@grapecity/spread-sheets').Spread.Sheets.Worksheet} sheet */
    setBindPath = (sheet, spread) => {
        var sheet = spread.getActiveSheet();
        var json = sheet.toJSON();
        var cells = json.data.dataTable;
        Object.keys(cells).map((row) => {
            Object.keys(cells[row]).map((col) => {
                var cell = cells[row][col] || {};
                var val = cell.value + "" || "";
                if (val.indexOf("{") > -1 && val.indexOf("}") > -1) {
                    var path = cell.value.match(/\{\s*?([^\s]*)\s*?\}/)[1];
                    sheet.setBindingPath(row, col, path);
                }
            });
        });
    };
    /**
     * @param {import('@grapecity/spread-sheets').Spread.Sheets.Worksheet} sheet
     * @param {object} data
     */
    setDataSource = (sheet, data) => {
        const dict = {
            FMG15_2: "1.党的机关 2.人大机关 3.行政机关 4.政协机关 5.监察机关 6.审判机关 7.检察机关 8.人民团体 9.事业单位 10.社团组织  11.其他 12.民主党派机关",
            FMG16_2: "1.科技机构 2.教育机构 3.文化机构 4.卫生机构 5.体育机构 6.机关后勤服务机构 7.其他行业",
            FMG18_2: "1.参公管理财政补助 2.非参公管理财政财政补助 3.自收自支",
            FMG17_2: "1.承担行政职能 2.公益一类 3.公益二类 4.从事生产经营活动 5.暂未明确类别",
        };
        var nd = {};
        Object.keys(data).map((v) => {
            nd[v] = data[v];
            if (dict[v]) {
                var dicArr = dict[v].split(/\s+/);
                dicArr.map((d) => {
                    var [c, l] = d.split(".");
                    if (l === data[v]) {
                        nd[v] = c;
                        nd[v + "_label"] = l;
                        nd[v + "_DICT"] = dict[v];
                    }
                });
            }
        });
        // console.log(nd);

        sheet.setDataSource(new GC.Spread.Sheets.Bindings.CellBindingSource(nd));
    };

    render() {
        const isNative = window.__isNative;
        return (
            <div className="componentContainer" style={this.props.style}>
                <div className="boxLeftRight">
                    {/* <div id="SheetGC" className="spreadContainer-left" style={{ width: "4405px", flex: "none" }}></div> */}
                    <div className="spreadContainer-left">
                        <div id="SheetGC" style={{ height: "100%" }}></div>
                        <div id="SheetGcStatus" style={{ width: "100%", height: "20px", marginBottom: "-20px" }}></div>
                    </div>

                    <div className="settingContainer-right">
                        <h3>公车管理示例</h3>
                        <div>
                            <p>以下示例展示如何使用表单上的属性。</p>
                        </div>
                        <button onClick={() => this.setPageBreak("set")}>设置分隔符</button>
                        <button onClick={() => this.setPageBreak("remove")}>删除分隔符</button>
                        <button onClick={() => this.setPageBreak("removeAll")}>重设所有分隔符</button>
                        <div>
                            纸张尺寸：
                            <select
                                value={this.state.paperSize}
                                onChange={(ev) => {
                                    this.setState({ paperSize: ev.target.value });
                                }}
                            >
                                <option value=""></option>
                                <option value="a4">A4</option>
                                <option value="a3">A3</option>
                            </select>
                        </div>
                        拆分与缩放比例互斥
                        <div>
                            列拆分为：
                            <input
                                type={"number"}
                                step="1"
                                value={this.state.fitPagesWide}
                                onChange={(ev) => {
                                    var v = ev.target.value;
                                    this.setState({ fitPagesWide: v });
                                    if (v) {
                                        this.setState({ zoomFactor: 100 });
                                    }
                                }}
                            />
                            页
                        </div>
                        <div>
                            缩放比例：
                            <input
                                type={"number"}
                                step="1"
                                value={this.state.zoomFactor}
                                onChange={(ev) => {
                                    this.setState({ zoomFactor: ev.target.value });
                                    this.setState({ fitPagesWide: -1 });
                                }}
                            />
                            %
                        </div>
                        <hr />
                        <button
                            onClick={() => {
                                this.handleSetPrintInfo();
                            }}
                        >
                            设置打印信息
                        </button>
                        <button
                            onClick={() => {
                                this.handlePrintData();
                            }}
                        >
                            打印当前Sheet
                        </button>
                        <button
                            onClick={() => {
                                this.handlePrintData("pdf");
                            }}
                        >
                            导出为 PDF
                        </button>
                        <button onClick={() => this.handlePrintData("html")}>导出为HTML</button>
                        <button disabled={!isNative} onClick={() => this.handlePrintData("electron")}>
                            electron 打印
                        </button>
                        <hr />
                        <table>
                            <tbody>
                                <tr>
                                    <td>
                                        <button
                                            onClick={() => {
                                                this.setLocalData();
                                            }}
                                        >
                                            根据LocalStorage设置模板
                                        </button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <button
                                            onClick={() => {
                                                this.setFileData();
                                            }}
                                        >
                                            根据文件数据设置表样
                                        </button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <select defaultValue={this.state.viewType} onChange={this.onChangeViewType}>
                                            {Object.keys(ViewType).map((v) => {
                                                return (
                                                    <option key={v} value={v}>
                                                        {ViewType[v]}
                                                    </option>
                                                );
                                            })}
                                        </select>
                                        视图模式
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        );
    }
}

export default SheetGC;
